<?php
/**
* Draw of advert types tbl
*/
function advert_configs()
{
$statuses=array(1=>'включено',0=>'выключено');
$content="<table border=0><tr><td valign='top'><h2>Оформления</h2>
<div>".l('Новый вид оформления','admin/config/advert/types/0/edit')."</div>";
  $rec=db_select('node_advert_types','nat')->fields('nat')->orderBy('name', 'ASC')->execute();
  $content.='<table border=1>
  <tr><th>Название</th><th>Описание</th><th>Цена</th><th>Статус</th></tr>';
 while($tr = $rec->fetchAssoc()) 
 {
 $content.='<tr><td>'.l($tr['name'],'admin/config/advert/types/'.$tr['id'].'/edit').'</td><td>'.$tr['description'].'</td><td>'.$tr['price'].'</td><td>'.$statuses[$tr['status']].'</td></tr>';
 #rint_r($tr);
 
 }
 $content.="</table><h2>Статусы Приватности</h2><div>".l('Новый вид оформления','admin/config/advert/private/0/edit')."</div>";
  $rec_private_types=db_select('node_advert_private_types','napt')->fields('napt')->orderBy('name', 'ASC')->execute();
  while($napt= $rec_private_types->fetchAssoc()) 
    {
    $content.='<li>'.l($napt['name']." за ".$napt['price'].' гр.','admin/config/advert/private/'.$napt['id'].'/edit',array('attributes'=>array('title'=>$napt['description']))).'</li>';
    }
 $content.='</td><td valign="top"><h2>Цены/Скидки за период публикации</h2>'.l('Новая скидка','admin/config/advert/period/0/edit')."
 <ul>";
  $rec_periods=db_select('node_advert_periods','nap')->fields('nap')->orderBy('period', 'ASC')->execute();
  while($nap = $rec_periods->fetchAssoc()) 
    {
    $content.='<li>'.l($nap['period']." дней за ".$nap['price']." гривен",'admin/config/advert/period/'.$nap['id'].'/edit').'</li>';
    }
    
 $content.='</ul></td><td valign="top"><h2>Количество символов в содержании</h2>'.l('Новый лимит','admin/config/advert/limit/0/edit').'<ul>';
 $rec_limits=db_select('node_advert_body_chars','nadc')->fields('nadc')->orderBy('chars_max', 'ASC')->execute();
  while($nads = $rec_limits->fetchAssoc()) 
    {
    $content.='<li>'.l('До '.$nads['chars_max']." символов = Цена * ".$nads['delta'],'admin/config/advert/limit/'.$nads['id'].'/edit').'</li>';
    }
 $content.='</ul></td></tr></table>';

 
#return system_settings_form($form);
return $content;
}
/**
*IMport adverts of inforpart from external system
**/
function advert_import_form($form,&$form_state)
{

$cities_rec=db_select("taxonomy_term_data","ttd")->fields("ttd")->condition('vid',6)->execute();
$cities[0]='нет';
while($city=$cities_rec->fetchObject())
{
#pre($city);
$cities[$city->tid]=$city->name;
}
#print_r($cities);
$form['#attributes'] = array('enctype' => "multipart/form-data");
$form['file']=array('#type'=>'file','#title'=>'Файл экспорта');
$form['type']=array('#type'=>'select','#title'=>'Тип выгрузки','#options'=>array('premier'=>'Премьер (khr)','fenix'=>'Феникс (XML)','cvs'=>'CVS (из эксель)'),'#required'=>true);
$form['status']=array('#type'=>'checkbox','#title'=>'Опубликованно','#default_value'=>1);
$form['city']=array('#type'=>'select','#title'=>'город публикации','#options'=>$cities);
$form['submit']=array('#type'=>'submit','#value'=>'Импорт');
return $form;
}
function _advert_tid2code($cat_id)
{
$sql="SELECT nat.code 
			FROM taxonomy_term_data ttd 
			LEFT JOIN node_advert_terms_taxonomy natt ON natt.tid=ttd.tid
			LEFT JOIN node_advert_terms nat ON nat.id=natt.node_advert_terms_id
			WHERE ttd.tid=".Q((int)$cat_id);
			#print $sql."<hr>";
  $cat=db_query($sql)->fetchObject();
			
  
return $cat->code;
}
function _advert_old_cat_id2tid($cat_id)
{
$sql="SELECT * FROM `taxonomy_term_data` WHERE old_cat_id LIKE '%".Q($cat_id,1)."%'";
#print $sql."<hr>";
$res=db_query($sql);
$cats=array();
while($r=$res->fetchObject())
  {
  
  $exp=explode(",",$r->old_cat_id);
  
  foreach($exp as $ex)
    {
    $cats[$ex]=$r->tid;
    }
  }
  
  foreach($cats as $old_cat_id=>$tid)
    {
    #print $old_cat_id."|".$cat_id."<hr>";
    
    if($old_cat_id==$cat_id)
      {
      $newtid=$tid;
      break;
      }
    }
return $newtid;  
}
/**
*Parsing text for find offers and advert_fields
*@param string $text=Text
*@param string $code=advert_Taxonomy code
*@return array $result;
*/
function _advert_parse_import_text($text,$code)
{
//get offers
#print $code;
	  $sql="SELECT ao.* FROM advert_offers_code aoc LEFT JOIN advert_offers ao ON ao.id=aoc.oid WHERE aoc.code='".Q($code,1)."'";
	  #print $sql."<hr>";
	  $offerc_rec=db_query($sql);
	  while($offer=$offerc_rec->fetchObject())
	  {
	  
	 #print $text."|".$offer->name."|".mb_stristr($text,$offer->name)."<hr>";
	  $all_offers[$offer->id]=$offer->id;
	  if(!empty($offer->name)&&mb_stristr($text,$offer->name))
	    {
	    #print $offer->name."<hr>";
	    $result['offers'][$offer->id]=$offer->id;
	    }
	  }
	  #pre($all_offers,1);
	  //choose all offers if not finded some
	  if((!isset($result['offers']))||(count($result['offers'])==0))
	  {
	  $result['offers']=$all_offers;
	  }
//get fields
#print "SELECT af.* FROM advert_fields_type aft LEFT JOIN advert_fields  af ON af.field=aft.field WHERE aft.type='".Q($code,1)."'";
	  $fields_rec=db_query("SELECT * FROM advert_fields  WHERE code='".Q($code,1)."'");
	  while($field=$fields_rec->fetchObject())
	  {
	  #
	  #print $text."|".$field->name."<hr>";
	  if(mb_stristr($text,$field->name))
	    {
	    #print $offer->name."<hr>";
	    #pre($field);
	    $result['custom_fields'][$field->field]=$field->name;
	    break;
	    }
	  }
	  #pre($result,1);
return $result;
}
function advert_import_error($tid,$cat_id,$code)
{
if(empty($code))
	    {
	    if(!$tid)
	    {
	    $msg=t("Импорт отвергнут. Старая Категория не заданна OLD_ID=".$cat_id);
	    }else{
	    $term=taxonomy_term_load($tid);
	    
	    
	    if($term->vid!=12)
	    {
	    $msg=t("Импорт отвергнут. Неверное определение  категории, Это `".$term->name."` не категория обьявлений!. TID=".$tid." OLD_ID=".$cat_id);
	    }else{
	    $msg=t("Импорт отвергнут. В заданной категории `".$term->name."` TID=".$tid." OLD_ID=".$cat_id." не установлен `вид рубрикатора`.Пожалуйста ".l('отредактируйте категорию','taxonomy/term/'.$tid."/edit"));
	    }
	    }
	    }elseif(empty($tid)){
	    $msg=t("Импорт отвергнут. Заданная категория OLD_ID=".$cat_id." не найдена");
	    }elseif(empty($cat_id)){
	    $msg=t("Импорт отвергнут. Отсутствует OLD_ID категории.");
	    }else{
	    $msg=t("Импорт отвергнут. Не найдены варианты предложений для заданной категории TID=".$tid." CODE=".$code." OLD_ID=".$cat_id);
	    }
	    
 drupal_set_message($msg, 'error');	    
}
function advert_import_form_submit($form,&$form_state)
{

 ini_set('max_execution_time',600);//10 min
$source_tmp=($_FILES['files']['tmp_name']['file']);
#print $source_tmp."<hr>";
$counter=0;
$city=$form_state['values']['city'];
  switch($form_state['values']['type'])
    {
    case 'premier':
		$content=file_get_contents($source_tmp);
		$content=mb_convert_encoding($content,'utf8','cp866');
		$rows=explode("\n",$content);
	
   	foreach($rows as $row)
	  {
	  if(!empty($row))
	  {
	  $cat_id=mb_substr($row,0,3);
	  $text=mb_substr($row,4);
	  //get code
	  $tid=_advert_old_cat_id2tid($cat_id);
	  
	  $code=_advert_tid2code($tid);
	 # die($code."<hr>");  
	  $data=_advert_parse_import_text($text,$code);
	  
	  //get 
	  
	  if(count($data['offers']))
	  {
	  _advert_node_save4import(array('data'=>$data,'tid'=>$tid,'city'=>$city,'text'=>$text,'period'=>7,'status'=>$form_state['input']['status'],'date'=>array(0=>date("Y-m-d"),1=>date("Y-m-d",strtotime("+1 day")))));
	  #die($text);
	  $counter++;
	  }else{
	   advert_import_error($tid,$cat_id,$code);
	  #drupal_set_message(t("Импорт отвергнут. Не найдены варианты предложений. Для зажанной категории TID=".$tid." CODE=".$code." OLD_ID=".$cat_id), 'error');
	  }
	  }
	  #print $text."<hr>";
	  
	  #die('next');
	  }
  
    break;
    case 'fenix':
    $content=simplexml_load_file($source_tmp);
    $max=count($content->media_plan);
    for($i=0;$i<$max;$i++)
    {
    $tid=_advert_old_cat_id2tid($content->media_plan[$i]->rubric_number);
    $code=_advert_tid2code($tid);
    $data=_advert_parse_import_text($content->media_plan[$i]->advert_text,$code);
    #pre($content->media_plan[$i]);
    #pre($data);
    #pre($form_state['input']['status']);
    #die($tid."<hr>");
     if(count($data['offers']))
	  {
    _advert_node_save4import(array('advert_id'=>$content->media_plan[$i]->advert_id,'data'=>$data,'tid'=>$tid,'city'=>$city,'period'=>7,'status'=>$form_state['input']['status'],'created'=>strtotime($content->media_plan[$i]->data_vyp),'text'=>$content->media_plan[$i]->advert_text,'date'=>array(0=>date("Y-m-d"),1=>date("Y-m-d",strtotime("+1 day")))));
    
	  $counter++;
	  }else{
	  advert_import_error($tid,$content->media_plan[$i]->rubric_number,$code);
	  }
	  
    }
    #parse_xml($content);
    break;
    case 'cvs':
      $content=file_get_contents($source_tmp);
      $content=mb_convert_encoding($content,'utf8','cp1251');
      $rows=explode("\n",$content);
      
      array_shift($rows);
      #pre($rows,1);
      foreach($rows as $row)
	  {
	  if(!empty($row))
	  {
	  $rowa=explode(";",$row);
	  $cat_id=$rowa[0];
	  $punkt=$rowa[1];
	  $created=strtotime(str_replace(".","-",$rowa[2]));
	  #pre($rowa[3]);
	  $dates=explode(",",$rowa[3]);
	  #for($t=strtotime($rowa[2]);$t<=strtotime($rowa[3]);$t+=24*3600)
	  for($i=0;$i<count($dates);$i++)
	    {
	   # print $t."<hr>";
	    $dates[$i]=date("Y-m-d",strtotime(str_replace(".","-",$dates[$i])));
	    }
	  $text=$rowa[4];
	 # pre($dates,1);
	  $tid=_advert_old_cat_id2tid($cat_id);
	  $code=_advert_tid2code($tid);
	  #pre($text);
	  $data=_advert_parse_import_text($text,$code);
	  if(count($data['offers']))
	  {
	  _advert_node_save4import(array('tid'=>$tid,'city'=>$city,
								'date'=>$dates,
								'text'=>$text,
								'period'=>count($dates),
								'data'=>$data,'status'=>$form_state['input']['status'],
								'created'=>$created));
	  $counter++;
	  }else{
	  advert_import_error($tid,$cat_id,$code);
	  
	  }
	  }
	  }
    break;
    }

unset($source_tmp);
drupal_set_message(t("Импорт принят. Импортированно ".$counter." обьявлений"), 'msg');
#die($counter."<hr>");
  $form_state['redirect'] = 'admin/config/advert/import';
}
/**
*save simple node item for import
*/
function _advert_node_save4import($var)
{
$node = new stdClass();
$node->type = 'advert';
node_object_prepare($node);
$node->title=mb_substr($var['text'],0,50);
$node->language = LANGUAGE_NONE;
/*$node->body[LANGUAGE_NONE][0]['value'] = $var['text'];
$node->body[LANGUAGE_NONE][0]['summary'] = strip_tags($var['text']);
$node->body[LANGUAGE_NONE][0]['format'] = 'filtered_html';*/
$node->uid=0;
$node->created=($var['created']?$var['created']:time());
$node->status = $var['status'];
$node->promote = 0;
if($node->tid)$node->taxonomy[]=$node->tid;
#pre($var['date']);
$node->pub_dates=isset($var['date'])?$var['date']:date("Y-m-d",strtotime("+1 day"));

node_save($node);
$nid=$node->nid;
$data=array(
'nid' => $nid,
'body'=>strip_tags($var['text']),
'field_type'=>'fresh',
'field_private_status'=>'private',
'field_price' => 0,
'field_price_optom'=>0,
'field_price_from'=>0,
'field_price_end'=>0,
'field_address'=>'',
'field_email'=>'',
'field_www'=>'',
'youtube_url'=>'',
'field_social'=>'',
'period'=>(($var['period']>7)?$var['period']:7),
'total_price'=>0,
'personal_name'=>'',
'bussiness_name'=>'',
'company_name'=>'');

$na=db_select("node_advert","na")->fields("na")->condition('nid',$nid)->execute()->fetchAssoc();

if(isset($na['nid']))
{
try { $id = db_update('node_advert')->fields($data)->condition('nid',$nid)->execute();} catch (Exception $e) {print_r($e);}
}else{

try { $id = db_insert('node_advert')->fields($data)->execute();}catch (Exception $e) {print_r($e);}
}

//offers
if(count($var['data']['offers']))
{
  _advert_save_offers($var['data'],$node);
}
//fields
if(count($var['data']['custom_fields']))
{
db_delete('node_advert_custom_fields')->condition('nid', $nid)->execute();
foreach($var['data']['custom_fields'] as $field=>$value)
  {
if(!empty($value))
      {
      $sql1="INSERT INTO node_advert_custom_fields (nid,field,value) VALUES (".$nid.",'".Q($field,1)."','".Q($value,1)."')";
   #   print $sql1;
      db_query($sql1);
      }
  }
}

//save taxonomy
db_delete('taxonomy_index')
  ->condition('nid', $nid)
  ->execute();
   try {
   #pre($var);
   #pre(array('tid'=>Q((int)$var['tid']),'nid'=>$nid,'created'=>time()));
  if($var['city']) db_insert('taxonomy_index')->fields(array('tid'=>Q((int)$var['city']),'nid'=>$nid,'created'=>time()))->execute();
  $id = db_insert('taxonomy_index')->fields(array('tid'=>Q((int)$var['tid']),'nid'=>$nid,'created'=>time()))->execute();
    } catch (Exception $e) {print_r($e);}
//save pubdates
if(count($node->pub_dates))
{
db_delete('node_advert_dates')
  ->condition('nid', $nid)
  ->execute();


foreach($node->pub_dates as $d)
  {
 # $d=str_replace("/","-",$d);
  $d=date('Y-m-d',strtotime($d));
  
	try {
	$data1=array('nid'=>$nid,'public_date'=>$d);
	#print $d."<hr>";
	$id = db_insert('node_advert_dates')->fields($data1)->execute();
	}catch (Exception $e) {pre($e,1);}

  }
}
#pre($node,1);
return true;
}
/**
*Draw element of field of admin for adverts fields
*/
function _advert_fields_get_field($type)
{

$rec_fields= db_select('advert_fields_type','aft')->fields('aft')->condition('type',$type['code'])->orderBy('weight', 'ASC')->execute();
#pre($type);
$output='<ul>';
$output.='<li>'.l(_('Виды предложений'),'admin/config/advert/offers/'.$type['code'].'/list').'</li>';
while($f=$rec_fields->fetchAssoc())
  {
  $output.='<li>'.l($f['name'],'admin/config/advert/fields/'.$f['field'].'/list').'    ('.l('ред. поле','admin/config/advert/fields/'.$f['field'].'/edit').')</li>';
  
  }
$output.='</ul>';
return $output;
}
/**
*Function draw admin of adverts fields
*/
function advert_fields_form()
{
$rec_types= db_select('#node_advert_terms','nat')->fields('nat')->orderBy('name', 'ASC')->execute();
#node_advert_terms
$output='<div>'.l('Новый тип рубрикатора','admin/config/advert/fields/0/typeedit').'&nbsp;'.l('Новое поле в рубрикаторе','admin/config/advert/fields/0/edit').'</div>';
$output.='<ul>';
while($type=$rec_types->fetchAssoc())
  {
  $output.='<li><h2>'.$type['name'].'</h2>'._advert_fields_get_field($type).'</li>';
  #print_r($type);
  }
$output.='</ul>';
return $output;
}
function advert_fieldtype_form($form,&$form_state)
{
$id=$form_state['build_info']['args'][0];

$form['name']=array('#type'=>'textfield','#title'=>'Название типа');

$form['code']=array('#type'=>'textfield','#title'=>'Код типа','#description'=>'Английский только');

for($i=0;$i<10;$i++)
{
$opt2[$i]=$i;
}
#$form['weight']=array('#type'=>'select','#title'=>'Вес','#options'=>$opt2);
$form['submit']=array('#type'=>'submit','#value'=>'Сохранить');
return $form;
}
function advert_fieldtype_form_submit($form,&$form_state)
{
try {$id = db_insert('node_advert_terms')->fields(array('name'=>Q($form_state['input']['name'],1),'code'=>Q($form_state['input']['code'],1)))->execute();} catch (Exception $e) {print_r($e);}

#die("<hr>");
$form_state['redirect'] = 'admin/config/advert/fields';
}
/**
*EDit Field type
*/
function advert_field_form($form,&$form_state)
{
$id=$form_state['build_info']['args'][0];
#print $id;
$node=db_select('advert_fields_type','aft')->fields('aft')->condition('field',$id)->execute()->fetchAssoc();
#pre($node);
$form['name']=array('#type'=>'textfield','#title'=>'Название поля','#default_value'=>$node['name']);
$rec_types= db_select('node_advert_terms','nat')->fields('nat')->orderBy('name', 'ASC')->execute();
$opt=array(0=>'-Выбрать тип-');
while($r=$rec_types->fetchAssoc())
{
$opt[$r['code']]=$r['name'];
}
$form['field']=array('#type'=>'textfield','#title'=>'Код поля','#description'=>'Английский только','#default_value'=>$node['field']);
#print $node['type'];
$form['type']=array('#type'=>'select','#title'=>'Тип рубрикатора','#options'=>$opt,'#default_value'=>$node['type']);
for($i=0;$i<10;$i++)
{
$opt2[$i]=$i;
}
#$form['form_type']=array('#type'=>'select','#title'=>'Тип элемента формы','#options'=>array('select'=>'Выпадающие списки','checkboxes'=>'Чекбоксы'),'#default_value'=>$node['form_type']);
$form['weight']=array('#type'=>'select','#title'=>'Вес','#options'=>$opt2,'#default_value'=>$node['weight']);
if($id)
{
$form['id']=array('#type'=>'hidden','#value'=>$node['id']);
}
$form['submit']=array('#type'=>'submit','#value'=>'Сохранить');
return $form;
}
function advert_field_form_submit($form,&$form_state)
{
if($form_state['input']['id'])
{

try { $id = db_update('advert_fields_type')->fields(array('name'=>Q($form_state['input']['name'],1),'type'=>Q($form_state['input']['type'],1),'field'=>$form_state['input']['field']))->condition('id',$form_state['input']['id'])->execute();} catch (Exception $e) {print_r($e);}
#pre($form_state['input']['id']);
#die("<hr>");
}else{
try {$id = db_insert('advert_fields_type')->fields(array('name'=>Q($form_state['input']['name'],1),'type'=>Q($form_state['input']['type'],1),'field'=>$form_state['input']['field'],'weight'=>$form_state['input']['weight']))->execute();} catch (Exception $e) {print_r($e);}
}

$form_state['redirect'] = 'admin/config/advert/fields';
}
/**
*Form for advert offer
*/
/*
function advert_offer_form($form,$form_state,$id)
{
$code=$form_state['build_info']['args'][1];
$form['title']=array('#type'=>'textfield','#title'=>'Название предложения');
$form['submit']=array('#type'=>'submit','#value'=>'сохранить');
#$form
$form['id']=array('#type'=>'hidden','#value'=>$id);
return $form;
}*/
/**
*Offer list
*/
function advert_offers_form($form,&$form_state,$code)
{
#$af_rec=db_select("advert_offers","ao")->fields("ao")->condition('code',$code)->execute();
#$af_rec=db_select("advert_offers","ao")->fields("ao")->execute();
$sql="SELECT DISTINCT ao.*,
SUM(aoc.code='".Q($code,1)."') as checked
FROM `advert_offers` ao 
LEFT JOIN advert_offers_code aoc ON aoc.oid=ao.id 
GROUP BY ao.id,ao.name
ORDER BY SUM(aoc.code='".Q($code,1)."')  DESC,ao.name";
#print $sql."<hr>";
$af_rec=db_query($sql);
while($aff=$af_rec->fetchObject()){$af[]=$aff;}
#pre($af);
#$afc_rec=db_select("advert_offers_code","aoc")->fields("aoc")->condition('code',$code)->execute();
#while($afcc=$afc_rec->fetchObject()){$afc[]=$afcc->oid;}



drupal_add_js("misc/advert.js");
$form['html']=array('#type'=>'html','#prefix'=>'<h5>Отмечайте галочками необходимые предложение, галочка означает принадлежность к данному типу</h5>');

if(!is_object($af)&&count($af))
{
$afjs='<script>';
$i=0;

foreach($af as $a)
  {
  #pre($a->name);
  #print $a->value;
  $afjs.="one_more_offer('offer','additional_offers','".$a->name."','".$a->id."',".(($a->checked)?1:0).");";
  $i++;
  }
$afjs.='</script>';
}
 $form['add_name'] = array(
    '#type' => 'button',
    '#value' => t('Добавить ещё'),
    '#attributes'=>array('onclick'=>"one_more_offer('offer','additional_offers',null,null,1);return false;"),
    '#submit' => array(''),
    '#prefix'=>'<div id="additional_offers"></div>',
    '#suffix'=>$afjs
    // See the examples in ajax_example.module for more details on the
    // properties of #ajax
  );
$form['code']=array('#type'=>'hidden','#value'=>$code);
#$form['submit']=array('#type'=>'submit','#value'=>'сохранить','#submit'=>array('_advert_offers_list_submit',$form,$form_state));
$form['submit']=array('#type'=>'submit','#value'=>'сохранить');
 #$rec= db_select('advert_fields','af')->fields('af')->condition('field',$field)->condition('parent',0)->orderBy('name', 'ASC')->execute();
 
 return $form;
}
function advert_offers_form_submit($form,&$form_state)
{


$code=$form_state['build_info']['args'][0];
$inp=$form_state['input'];
#array_values($inp['oids'])
/*
foreach($inp['oids'] as $oid)
  {
  if(!empty($oid))$oids[]=$oid;
  }*/

  
  
if(count($inp['offer']))
  {
  db_query("DELETE FROM advert_offers_code WHERE code='".Q($code,1)."'");
  #db_query("DELETE FROM advert_offers_code WHERE code='".Q($code,1)."' AND id NOT IN (".implode(',',$oids).")");
#db_delete('advert_offers')->condition('code', Q($code,1))->execute();

  foreach($inp['offer'] as $offer_oid=>$offer_name)
    {
    $offer_ooid=$offer_oid;
    
    if(!empty($offer_name))
    {
    
    if(substr($offer_oid,0,4)=='next')
      {
      
      try {$offer_ooid= db_insert('advert_offers')->fields(array('name'=>Q($offer_name,1)))->execute();} catch (Exception $e) {print_r($e);}

      }else{
    #pre(Q($offer_name,1));
     try { db_update('advert_offers')->fields(array('name'=>Q($offer_name,1)))->condition('id',$offer_oid)->execute();} catch (Exception $e){print_r($e);}      
    
	}
	
	
	if($inp['oids_status'][$offer_oid]=='on'){try {db_insert('advert_offers_code')->fields(array('oid'=>$offer_ooid,'code'=>$code))->execute();} catch (Exception $e) {print_r($e);}}
	
    }
   
    }
     
  }
  


$form_state['redirect'] = 'admin/config/advert/fields'; 

}
function advert_fields_list($field)
{
drupal_add_js("misc/advert.js");


#$form['field']=array('#type'=>'hidden','#value'=>$field);
$out='<div>'.l('добавить элемент','admin/config/advert/fields/0/'.$field.'/edit').'</div>';
 $rec= db_select('advert_fields','af')->fields('af')->condition('field',$field)->condition('parent',0)->orderBy('name', 'ASC')->execute();
   # $options=array(0=>'нет');
  $out.='<ul>'; 
 while($t = $rec->fetchAssoc()) 
 {
 $out.='<li><a href="javascript://" onClick="advert_openbox(\'field'.$t['id'].'\')">'.$t['name'].'</a> | '.l('ред.','admin/config/advert/fields/'.$t['id'].'/'.$t['field'].'/edit');
 
 switch($field)
 {
 case 'car_brand':
 case 'staff_type':
 case 'animal_type':
 case 'moto_type':
 case 'hobby_type':
 $out.='<ul id="field'.$t['id'].'" style="display:none;">';
 $out.='<li>'.l('Новая подрубрика','admin/config/advert/fields/0/'.$t['id'].'/'.$t['field'].'/edit').'</li>';
 $rec1= db_select('advert_fields','af')->fields('af')->condition('field',$field)->condition('parent',$t['id'])->orderBy('name', 'ASC')->execute();
  while($t1 = $rec1->fetchAssoc()) 
    {
    $out.='<li>'.$t1['name'].' '.l('ред.','admin/config/advert/fields/'.$t1['id'].'/'.$t1['parent'].'/'.$t1['field'].'/edit').'</li>';
    }  
 $out.='</ul>';
 break;
 }
 $out.='</li>';
 #.
 #$out.='<li>'.l($t['name'],'admin/config/advert/fields/'.$t['id'].'/'.$t['field'].'/edit').' | '.l('Создать подрубрику','admin/config/advert/fields/0/'.$t['id'].'/'.$t['field'].'/edit').'</li>';
  #$options[$term['id']]=$term['name'];
    #$node->public_dates[$pd['id']]=$pd['public_date'];
 }
$out.='</ul>';
return $out;
}
function advert_fields_item_child_form($form,&$form_state)
{

$id=$form_state['build_info']['args'][0];
$parent=$form_state['build_info']['args'][1];
$field=$form_state['build_info']['args'][2];
 
 $node= db_select('advert_fields','af')->fields('af')->condition('field',$field)->condition('id',$id)->execute()->fetchAssoc();
 $parent_node=db_select('advert_fields','af')->fields('af')->condition('field',$field)->condition('id',$parent)->execute()->fetchAssoc();
$form['h']=array('#type'=>'html','#prefix'=>'<h2>Подэлемент элемента <font color="red">'.$parent_node['name'].'</font></h2>'); 
#$form=drupal_get_form('advert_fields');
$form['parent']=array('#type'=>'hidden','#value'=>$parent_node['id']);
$form['name']=array('#type'=>'textfield','#title'=>'Название','#default_value'=>$node['name']);
$form['field']=array('#type'=>'hidden','#value'=>$field);
$form['id']=array('#type'=>'hidden','#value'=>$id);
$form['submit']=array('#type'=>'submit','#value'=>'Сохранить');
if($id)$form['delete']=array('#type'=>'submit','#value'=>'Удалить');
#$form['submit'][]=
return $form;

}
function advert_fields_item_child_form_submit($form, &$form_state)
{
if($form_state['input']['op']=='Сохранить')
{

if($form_state['input']['id'])
  {
  try { $id = db_update('advert_fields')->fields(array('name'=>Q($form_state['input']['name'],1),'field'=>Q($form_state['build_info']['args'][2],1),'parent'=>$form_state['build_info']['args'][1]))->condition('id',$form_state['input']['id'])->execute();} catch (Exception $e) {drupal_set_message(t("Sorry, that didn't work. The name must be unique."), 'error');}
  }else{
  try {$id = db_insert('advert_fields')->fields(array('name'=>Q($form_state['input']['name'],1),'field'=>Q($form_state['build_info']['args'][2],1),'parent'=>$form_state['build_info']['args'][1]))->execute();} catch (Exception $e) {print_r($e);}
  }
#pre($form_state['input']['name']);
#pre($form_state['build_info']['args'][1]);

}elseif($form_state['input']['op']=='Удалить')
{
db_delete('advert_fields')->condition('id', $form_state['input']['id'])->execute();
}

$form_state['redirect'] = 'admin/config/advert/fields/'.$form_state['build_info']['args'][2].'/list';
}
/**
*Edit item list of field types
*/
function advert_fields_item_form($form,&$form_state)
{

$id=$form_state['build_info']['args'][0];
$field=$form_state['build_info']['args'][1];
 
 $node= db_select('advert_fields','af')->fields('af')->condition('field',$field)->condition('id',$id)->execute()->fetchAssoc();
 #pre($node);
#$form=drupal_get_form('advert_fields');

$form['name']=array('#type'=>'textfield','#title'=>'Название','#default_value'=>$node['name']);
$form['field']=array('#type'=>'hidden','#value'=>$field);
$form['id']=array('#type'=>'hidden','#value'=>$id);
$form['submit']=array('#type'=>'submit','#value'=>'Сохранить');
if($id)$form['delete']=array('#type'=>'submit','#value'=>'Удалить');
#$form['submit'][]=
return $form;
}
function advert_fields_item_form_submit($form, &$form_state)
{

if($form_state['input']['op']=='Сохранить')
{

if($form_state['input']['id'])
  {
  
  try { $id = db_update('advert_fields')->fields(array('name'=>Q($form_state['input']['name'],1),'field'=>Q($form_state['build_info']['args'][1],1)))->condition('id',$form_state['input']['id'])->execute();} catch (Exception $e) {drupal_set_message(t("Sorry, that didn't work. The name must be unique."), 'error');}
  }else{
  
  $h= db_select('advert_fields_type','aft')->fields('aft')->condition('field',$form_state['input']['field'])->execute()->fetchAssoc();
try {$id = db_insert('advert_fields')->fields(array('name'=>Q($form_state['input']['name'],1),'field'=>Q($form_state['build_info']['args'][1],1),'code'=>$h['type']))->execute();} catch (Exception $e) {print_r($e);}
#die("<hr>");
  }

#pre($form_state['build_info']['args'][1]);

}elseif($form_state['input']['op']=='Удалить')
{
db_delete('advert_fields')->condition('id', $form_state['input']['id'])->execute();
}
#pre(array('name'=>Q($form_state['input']['name'],1),'field'=>Q($form_state['build_info']['args'][1],1)));
#pre($form_state,1);
$form_state['redirect'] = 'admin/config/advert/fields/'.$form_state['build_info']['args'][1].'/list';
}
/**
* hook_form()
* advert private new/edit
*/
function advert_private_form($form, &$form_state)
{
$id=$form_state['build_info']['args'][0];
if($id)
{
$node=db_select("`node_advert_private_types","napt")->fields('napt')->condition('id',$id)->execute()->fetchAssoc();
}
$form['name']=array('#type'=>'textfield',
		      '#title'=>'Название приватного статуса',
#		      '#prefix'=>'<table><tr><td>',
#		      '#suffix'=>'</td>',
		      '#default_value'=>isset($node['name'])?$node['name']:'');
$form['code']=array('#type'=>'textfield',
		      '#title'=>'Код для программирования события',
#		      '#prefix'=>'<table><tr><td>',
#		      '#suffix'=>'</td>',
		      '#default_value'=>isset($node['code'])?$node['code']:'');		      
$form['description']=array('#type'=>'textarea',
		      '#title'=>'Описание',
#		      '#prefix'=>'<td>',
#		      '#suffix'=>'</td>',
#		      '#description'=>'Цена за публикацию на данный период',
		      '#default_value'=>isset($node['description'])?$node['description']:'');		      
$form['price']=array('#type'=>'textfield',
		      '#title'=>'Цена',
#		      '#prefix'=>'<td>',
#		      '#suffix'=>'</td>',
#		      '#description'=>'Цена',
		      '#default_value'=>isset($node['price'])?$node['price']:0);
$form['submit'][0]=array('#type'=>'submit',
#		      '#prefix'=>'<td>',
#		      '#suffix'=>'</td>',
		      '#name'=>'op',
		      '#value'=>'Записать');		      		      		      
		      
$form['submit'][1]=array('#type'=>'submit',
#		      '#prefix'=>'<td>',
#		      '#suffix'=>'</td></tr></table>',
		      '#name'=>'op',
		      '#value'=>'Удалить');		      		      
$form['id']=array('#type'=>'hidden','#value'=>$id);
return $form;		      
}
/**
* hook_form_submit()
* advert private new/edit
*/
function advert_private_form_submit($form, &$form_state)
{
$inp=$form_state['input'];
if($inp['op']=='Удалить')
{
//taxonomy
db_delete('node_advert_private_types')->condition('id', $inp['id'])->execute();
}else{
if($inp['id'])
{
try { $id = db_update('node_advert_private_types')->fields(array('name'=>Q($inp['name'],1),'code'=>Q($inp['code'],1),'description'=>Q($inp['description'],1),'price'=>Q((int)$inp['price'])))->condition('id',$inp['id'])->execute();} catch (Exception $e) {drupal_set_message(t("Sorry, that didn't work. The name must be unique."), 'error');}
}else{
 try {$id = db_insert('node_advert_private_types')->fields(array('name'=>Q($inp['name'],1),'code'=>Q($inp['code'],1),'description'=>Q($inp['description'],1),'price'=>Q((int)$inp['price'])))->execute();} catch (Exception $e) {print_r($e);}
}
}
#die($inp['name']."<hr>");
$form_state['redirect'] = 'admin/config/advert/types';
}
/**
* hook_form()
* advert limit new/edit
*/
function advert_limit_form($form, &$form_state)
{
$id=$form_state['build_info']['args'][0];
if($id)
{
$node=db_select("node_advert_body_chars","nads")->fields('nads')->condition('id',$id)->execute()->fetchAssoc();
}
$form['chars_max']=array('#type'=>'textfield',
		      '#title'=>'Максимальное количество символов',
		      '#prefix'=>'<table><tr><td>',
		      '#suffix'=>'</td>',
		      '#description'=>'Верхняя Граница количества текста в содержании обьявления',
		      '#default_value'=>isset($node['chars_max'])?$node['chars_max']:0);
$form['delta']=array('#type'=>'textfield',
		      '#title'=>'Делта влияния на цену',
		      '#prefix'=>'<td>',
		      '#suffix'=>'</td>',
		      '#description'=>'Цена будет умноженна на заданное количество раз',
		      '#default_value'=>isset($node['delta'])?$node['delta']:0);
$form['submit'][0]=array('#type'=>'submit',
		      '#prefix'=>'<td>',
		      '#suffix'=>'</td>',
		      '#name'=>'op',
		      '#value'=>'Записать');		      		      		      
		      
$form['submit'][1]=array('#type'=>'submit',
		      '#prefix'=>'<td>',
		      '#suffix'=>'</td></tr></table>',
		      '#name'=>'op',
		      '#value'=>'Удалить');		      		      
$form['id']=array('#type'=>'hidden','#value'=>$id);
return $form;		      
}
/**
* hook_form_submit()
* advert limit new/edit
*/
function advert_limit_form_submit($form, &$form_state)
{
$inp=$form_state['input'];
if($inp['op']=='Удалить')
{
//taxonomy
db_delete('node_advert_body_chars')->condition('id', $inp['id'])->execute();
}else{
if($inp['id'])
{
try { $id = db_update('node_advert_body_chars')->fields(array('chars_max'=>Q((int)$inp['chars_max']),'delta'=>Q((int)$inp['delta'])))->condition('id',$inp['id'])->execute();} catch (Exception $e) {drupal_set_message(t("Sorry, that didn't work. The name must be unique."), 'error');}
}else{
 try {$id = db_insert('node_advert_body_chars')->fields(array('chars_max'=>Q((int)$inp['chars_max']),'delta'=>Q((int)$inp['delta'])))->execute();} catch (Exception $e) {print_r($e);}
}
}
$form_state['redirect'] = 'admin/config/advert/types';
}
/**
* hook_form()
* advert period new/edit
*/
function advert_period_form($form, &$form_state)
{
$id=$form_state['build_info']['args'][0];
if($id)
{
$node=db_select("node_advert_periods","nap")->fields('nap')->condition('id',$id)->execute()->fetchAssoc();
}
$form['period']=array('#type'=>'textfield',
		      '#title'=>'Период (дни)',
		      '#prefix'=>'<table><tr><td>',
		      '#suffix'=>'</td>',
		      '#description'=>'Сколько дней публикации за данную скидку',
		      '#default_value'=>isset($node['period'])?$node['period']:0);
$form['price']=array('#type'=>'textfield',
		      '#title'=>'Цена',
		      '#prefix'=>'<td>',
		      '#suffix'=>'</td>',
		      '#description'=>'Цена за публикацию на данный период',
		      '#default_value'=>isset($node['price'])?$node['price']:0);
$form['submit'][0]=array('#type'=>'submit',
		      '#prefix'=>'<td>',
		      '#suffix'=>'</td>',
		      '#name'=>'op',
		      '#value'=>'Записать');		      		      		      
		      
$form['submit'][1]=array('#type'=>'submit',
		      '#prefix'=>'<td>',
		      '#suffix'=>'</td></tr></table>',
		      '#name'=>'op',
		      '#value'=>'Удалить');		      		      
$form['id']=array('#type'=>'hidden','#value'=>$id);
return $form;		      
}
function advert_period_form_submit($form, &$form_state)
{
$inp=$form_state['input'];
if($inp['op']=='Удалить')
{
//taxonomy
db_delete('node_advert_periods')->condition('id', $inp['id'])->execute();
}else{
if($inp['id'])
{
try { $id = db_update('node_advert_periods')->fields(array('period'=>Q((int)$inp['period']),'price'=>Q((int)$inp['price'])))->condition('id',$inp['id'])->execute();} catch (Exception $e) {drupal_set_message(t("Sorry, that didn't work. The name must be unique."), 'error');}
}else{
 try {$id = db_insert('node_advert_periods')->fields(array('period'=>Q((int)$inp['period']),'price'=>Q((int)$inp['price'])))->execute();} catch (Exception $e) {print_r($e);}
}
}
$form_state['redirect'] = 'admin/config/advert/types';
}
/**
* hook_form()
* advert type new/edit
*/
function advert_configs_form($form, &$form_state)  {
$id=$form_state['build_info']['args'][0];
if($id)
{
$node=db_select('node_advert_types','nat')->fields('nat')->condition('id',$id)->execute()->fetchAssoc();
#pre($node);
}else{
$node=$form_state['input'];

}
#die($id."<hr>");
  // Demo Page Title

  
  $form['advert']['new']=array('#type'=>'fieldset','#title'=>'Новый тип обьявлений','#description' => t('Помните! Новый вид обьявлений небудет работать без поддержки программиста (PHP).'));
  $form['advert']['new']['name'] = array(
    '#type' => 'textfield',
    '#title' => 'Название Вида',
    '#description'=>'Наименование демонстрируемое людям',
    '#max_length' => 100,
    '#size' => 20,
    '#required' => TRUE,
    '#default_value' => $node['name']
  );
  $form['advert']['new']['description'] = array(
    '#type' => 'textarea',
    '#title' => 'Описание',
    '#description'=>'Вспомогательное описание вида',
    '#max_length' => 100,
    '#cols' => 2,
    '#required' => TRUE,
    '#default_value' => $node['description']
  );
  $form['advert']['new']['code'] = array(
    '#type' => 'textfield',
    '#title' => 'Служебный Код вида',
    '#description'=>'Используется разработчиком - для перехвата события',
    '#max_length' => 100,
    '#size' => 20,
    '#required' => TRUE,
     '#default_value' => $node['code']
  );
  $form['advert']['new']['price'] = array(
    '#type' => 'textfield',
    '#title' => 'Надбавка к цене обьявления',
    '#max_length' => 100,
    '#description'=>'Базовая Цена за вид обьявление',
    '#size' => 5,
    '#required' => TRUE,
    '#default_value' => $node['price']
  );
  $form['advert']['new']['status'] = array(
    '#type' => 'radios',
    '#title' => 'Статус',
    '#max_length' => 100,
    '#options'=>array(1=>'включено',0=>'выключено'),
    '#required' => TRUE,
    '#default_value' => $node['status']
  );

  $form['advert']['new']['id'] = array(
    '#type' => 'hidden',
    '#value' => (isset($node['id'])?$node['id']:0),
  );
  $form['advert']['new']['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Сохранить',
  );
  #return system_settings_form($form);
  return $form;
}
/**
*hook_form_submit()
*advert type
*/
function advert_configs_form_submit($form,&$form_state)
{
 $inp=$form_state['input'];
 $data=array('name'=>$inp['name'],'description'=>$inp['description'],'code'=>$inp['code'],'price'=>$inp['price'],'status'=>$inp['status']);

 if($inp['id']==0)
 {
 //insert
 
 try { $id = db_insert('node_advert_types')->fields($data)->execute();}catch (Exception $e) {  drupal_set_message(t("Sorry, that didn't work. The name must be unique."), 'error');}
 }else{
  
 //update
 $data['id']=$inp['id'];
 try { $id = db_update('node_advert_types')->fields($data)->condition('id', $inp['id'])->execute();} catch (Exception $e) {drupal_set_message(t("Sorry, that didn't work. The name must be unique."), 'error');}
 #pre($data,1);
 }
$form_state['redirect'] = 'admin/config/advert/types';
}
function advert_form_alter(&$form, &$form_state, $form_id) {

switch($form_id)  
{
  case 'taxonomy_overview_terms':
  array_unshift($form['#theme'], 'advert_taxonomy_overview_terms');
  break;
 case 'node_admin_content':
//test bof
/*
    $header = $form['admin']['nodes']['#header'];
    $rows = $form['admin']['nodes']['#options'];

    $header['custom'] = array(
      'data' => 'Custom',
      'field' => 'n.custom'
    );

    $rows['5']['custom'] = 'Custom data';

    $form['admin']['nodes']['#header'] = $header;
    $form['admin']['nodes']['#options'] = $rows;
 */   
    //test eof
    #pre(strip_tags($form['filter']['filters']['current'][0]['#markup']));
    /*
    if(trim(strip_tags($form['filter']['filters']['current'][0]['#markup']))=='тип — Объявление')
    {
    $form['filter']['filters']['field_type']=array('#type'=>'select','#title'=>'Виды обьявлений','#options'=>array('fresh'=>'свежие','рекомендованные'));
    $form['filter']['filters']['field_private_status']=array('#type'=>'select','#options'=>array('private'=>'частное','bussiness'=>'деловое'),'#title'=>'Частное/деловое');
    $form['filter']['filters']['field_filter_type']=array('#type'=>'select','#options'=>array('buy'=>'Куплю','sell'=>'Продам'),'#title'=>'Куплю/Продам');
    }*/
    #$form['filter']['field_type']=array('type'=>'')
  break;  
  case 'taxonomy_form_term':
  ### hack for taxonomy term form
  if(is_object($form['#term']))
  {
  $vid=$form['#term']->vid;
  $tid=$form['#term']->tid;
  }else{
  $vid=$form['#term']['vid'];
  $tid=$form['#term']['tid'];
  }
 $term=db_select('taxonomy_term_data','ttd')->fields('ttd')->condition('tid',$tid)->execute()->fetchAssoc();
 $vocabulary_machine_name=((is_object($form['#term']))?$form['#term']->vocabulary_machine_name:$form['#term']['vocabulary_machine_name']);
  $form['meta_keywords']=array('#type'=>'textfield',
                                '#title'=>'Мета Слова',
                                '#size'=>156,
                                '#max_length'=>255,
                                '#description'=>'Слова поиска,в порядке важности через запятую (билет, афиша, театры)',
                                '#default_value'=>($term['meta_keywords']?$term['meta_keywords']:'')
                                );
  $form['#submit'][] = 'taxonomy_term_form_meta_submit';
  switch($vocabulary_machine_name)
  {
  case 'advert_cat':
    $terms_rec = db_select('node_advert_terms','nat')->fields('nat')->orderBy('name', 'ASC')->execute();
    $options=array(0=>'нет');
 while($term = $terms_rec->fetchAssoc()) 
 {
  $options[$term['id']]=$term['name'];
 }

  $cur=db_select('node_advert_terms_taxonomy','natt')->fields('natt')->condition('tid',$tid)->execute()->fetchAssoc();
  
  $form['advert_type']=array('#type'=>'select',
			     '#title'=>'Вид рубрикатора обьявлений',
			      
			     '#description'=>'Используется только в рубрикаторах обьявлений для выбора динамичных вспомогательных полей',
			     '#options'=>$options,
			     '#default_value'=>($cur['node_advert_terms_id']?$cur['node_advert_terms_id']:'')
			     );
			     
  $form['old_cat_id']=array('#type'=>'textfield','#title'=>'ID программы премьер',
  '#description'=>'Впишите ID для связей 2 разных рубрикаторов. Используйте "," для разделения нескольких ID','#default_value'=>($term['old_cat_id']?$term['old_cat_id']:''));
  $form['#submit'][] = 'advert_taxonomy_term_form_submit';	
break;  
case 'category_of_events':

	$form['id_cat_karabas']=array('#type'=>'textfield','#title'=>'ID Рубрики Карабас','#default_value'=>($term['id_cat_karabas']?$term['id_cat_karabas']:''));
	$form['id_cat_inetbilet']=array('#type'=>'textfield','#title'=>'ID Рубрики И-нет Билет','#default_value'=>($term['id_cat_inetbilet']?$term['id_cat_inetbilet']:''));
        
	$form['#submit'][] = 'events_taxonomy_term_form_submit';
	break;
	case 'city':
  
  ## hack for cities
  $city=db_select('citydomain','c')->fields('c')->condition('tid',$tid)->execute()->fetchAssoc();
  
  $form['subdomain']=array('#type'=>'textfield','#title'=>'Домэйн URL','#default_value'=>$city['url']);
  $form['#submit'][] = 'advert_taxonomy_term_form_city_submit';
  break;
  }			      
  #print $vid;
  break;
  }
  
  
}
/**
* Implements hook_theme().
*/
function taxonomy_term_form_meta_submit($form, &$form_state)
{
 
    try { 
        $id = db_update('taxonomy_term_data')
                ->fields(array('meta_keywords'=>$form['meta_keywords']['#value']))
                ->condition('tid',$form['#term']['tid'])->execute();
        
    } catch (Exception $e) {
        print_r($e);die("error");
    
    }
  
  
}
function advert_theme() {
  return array(
    'advert_taxonomy_overview_terms' => array(
      'render element' => 'form',
    ),
  );
}
/**
* THEME FOR OVERWRITE taxonomy_overview_terms
*/
function theme_advert_taxonomy_overview_terms($variables) {
 $form = $variables['form'];

  $page_increment  = $form['#page_increment'];
  $page_entries    = $form['#page_entries'];
  $back_step     = $form['#back_step'];
  $forward_step  = $form['#forward_step'];

  // Add drag and drop if parent fields are present in the form.
  if ($form['#parent_fields']) {
    drupal_add_tabledrag('taxonomy', 'match', 'parent', 'term-parent', 'term-parent', 'term-id', FALSE);
    drupal_add_tabledrag('taxonomy', 'depth', 'group', 'term-depth', NULL, NULL, FALSE);
    drupal_add_js(drupal_get_path('module', 'taxonomy') . '/taxonomy.js');
    drupal_add_js(array('taxonomy' => array('backStep' => $back_step, 'forwardStep' => $forward_step)), 'setting');
    drupal_add_css(drupal_get_path('module', 'taxonomy') . '/taxonomy.css');
  }
  drupal_add_tabledrag('taxonomy', 'order', 'sibling', 'term-weight');

  $errors = form_get_errors() != FALSE ? form_get_errors() : array();
  $rows = array();
  foreach (element_children($form) as $key) {
    if (isset($form[$key]['#term'])) {
      $term = &$form[$key];

      $row = array();
      $row[] = (isset($term['#term']['depth']) && $term['#term']['depth'] > 0 ? theme('indentation', array('size' => $term['#term']['depth'])) : ''). drupal_render($term['view']);
      if ($form['#parent_fields']) {
        $term['tid']['#attributes']['class'] = array('term-id');
        $term['parent']['#attributes']['class'] = array('term-parent');
        $term['depth']['#attributes']['class'] = array('term-depth');
        $row[0] .= drupal_render($term['parent']) . drupal_render($term['tid']) . drupal_render($term['depth']);
      }
      $term['weight']['#attributes']['class'] = array('term-weight');
      #pre($term['edit']);
      $term['old_cat_id']=array('#type'=>'html','#prefix'=>$term['#term']['old_cat_id']);
      
      $row[] = drupal_render($term['weight']);
      $row[]=drupal_render($term['old_cat_id']);
      $row[] = drupal_render($term['edit']);
      $row = array('data' => $row);
      $rows[$key] = $row;
    }
  }

  // Add necessary classes to rows.
  $row_position = 0;
  foreach ($rows as $key => $row) {
    $rows[$key]['class'] = array();
    if (isset($form['#parent_fields'])) {
      $rows[$key]['class'][] = 'draggable';
    }

    // Add classes that mark which terms belong to previous and next pages.
    if ($row_position < $back_step || $row_position >= $page_entries - $forward_step) {
      $rows[$key]['class'][] = 'taxonomy-term-preview';
    }

    if ($row_position !== 0 && $row_position !== count($rows) - 1) {
      if ($row_position == $back_step - 1 || $row_position == $page_entries - $forward_step - 1) {
        $rows[$key]['class'][] = 'taxonomy-term-divider-top';
      }
      elseif ($row_position == $back_step || $row_position == $page_entries - $forward_step) {
        $rows[$key]['class'][] = 'taxonomy-term-divider-bottom';
      }
    }

    // Add an error class if this row contains a form error.
    foreach ($errors as $error_key => $error) {
      if (strpos($error_key, $key) === 0) {
        $rows[$key]['class'][] = 'error';
      }
    }
    $row_position++;
  }

  if (empty($rows)) {
    $rows[] = array(array('data' => $form['#empty_text'], 'colspan' => '3'));
  }

  $header = array(t('Name'), t('Weight'),t('ID Премьер'), t('Operations'));
  $output = theme('table', array('header' => $header, 'rows' => $rows, 'attributes' => array('id' => 'taxonomy')));
  $output .= drupal_render_children($form);
  #$output .= theme('pager');

  return $output;
}
function advert_taxonomy_term_form_city_submit($form, &$form_state) {
$subdomain=trim($form['subdomain']['#value']);

if(is_object($form['#term']))
  {
 
  $tid=$form['#term']->tid;
  $name=$form['#term']->name;
  }else{
 $name=$form['#term']['name'];
  $tid=$form['#term']['tid'];
  }
  

#db_delete('citydomain')->condition('tid', $tid)->execute();
$city=db_select("citydomain","c")->fields("c")->condition('tid',$tid)->execute()->fetchAssoc();

if(isset($city['id']))
{
if(empty($subdomain))
{
db_delete('citydomain')->condition('tid',$tid)->execute();
}else{
try {$id = db_update('citydomain')->fields(array('url'=>$subdomain,'name'=>$name))->condition('tid',$tid)->execute();}catch (Exception $e) {pre($e);	}
}
}elseif(!empty($subdomain)){
#die('insert');
    try {$id = db_insert('citydomain')->fields(array('tid'=>$tid,'url'=>$subdomain,'name'=>$name))->execute();}catch (Exception $e) {pre($e);	}
    }
 #   pre($city,1);
}
function events_taxonomy_term_form_submit($form, &$form_state) {

    // do what you want to do after registration
  if(is_object($form['#term']))
  {
 
  $tid=$form['#term']->tid;
  }elseif($form['#term']['tid']){
 
  $tid=$form['#term']['tid'];
  }elseif($form['field_public_dates1']['und']['#entity']->tid){
  $tid=$form['field_public_dates1']['und']['#entity']->tid;
  }

 #   db_delete('node_advert_terms_taxonomy')->condition('tid', $tid)->execute();
    
   
	try { $id = db_update('taxonomy_term_data')->fields(array(
	'id_cat_karabas'=>$form['id_cat_karabas']['#value'],
	'id_cat_inetbilet'=>$form['id_cat_inetbilet']['#value']))->condition('tid',$tid)->execute();} catch (Exception $e) {print_r($e);die("error");}
  
}
/**
*Submit taxonomy_term_form alter
*/
function advert_taxonomy_term_form_submit($form, &$form_state) {

    // do what you want to do after registration
  if(is_object($form['#term']))
  {
 
  $tid=$form['#term']->tid;
  }elseif($form['#term']['tid']){
 
  $tid=$form['#term']['tid'];
  }elseif($form['field_public_dates1']['und']['#entity']->tid){
  $tid=$form['field_public_dates1']['und']['#entity']->tid;
  }
 
    db_delete('node_advert_terms_taxonomy')->condition('tid', $tid)->execute();
    
    try {
	
	$id = db_insert('node_advert_terms_taxonomy')->fields(array('tid'=>$tid,'node_advert_terms_id'=>$form['advert_type']['#value']))->execute();
	}catch (Exception $e) {
	pre($e,1);

	}
	try { $id = db_update('taxonomy_term_data')->fields(array('old_cat_id'=>$form['old_cat_id']['#value']))->condition('tid',$tid)->execute();} catch (Exception $e) {print_r($e);}
  
}
?>